package com.ferryc.commons.utils;

import java.io.UnsupportedEncodingException;
import java.util.Collection;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringEscapeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

/**
 * 
 * <pre>
 * 【类型】: StringUtils <br/> 
 * 【作用】: 继承自Spring util的工具类，减少jar依赖. <br/>  
 * 【时间】：2017年5月23日 上午10:00:47 <br/> 
 * 【作者】：Ferry Chen <br/>
 * </pre>
 */
public class StringUtil extends StringUtils {
	private static Logger log = LoggerFactory.getLogger(StringUtil.class);

	public static final String EMPTY = "";

	/**
	 * Check whether the given {@code CharSequence} contains actual
	 * <em>text</em>.
	 * <p>
	 * More specifically, this method returns {@code true} if the
	 * {@code CharSequence} is not {@code null}, its length is greater than 0,
	 * and it contains at least one non-whitespace character.
	 * <p>
	 * 
	 * <pre class="code">
	 * StringUtils.isBlank(null) = true
	 * StringUtils.isBlank("") = true
	 * StringUtils.isBlank(" ") = true
	 * StringUtils.isBlank("12345") = false
	 * StringUtils.isBlank(" 12345 ") = false
	 * </pre>
	 * 
	 * @param cs
	 *            the {@code CharSequence} to check (may be {@code null})
	 * @return {@code true} if the {@code CharSequence} is not {@code null}, its
	 *         length is greater than 0, and it does not contain whitespace only
	 * @see Character#isWhitespace
	 */
	public static boolean isBlank(final CharSequence cs) {
		return !StringUtil.isNotBlank(cs);
	}

	/**
	 * <p>
	 * Checks if a CharSequence is not empty (""), not null and not whitespace
	 * only.
	 * </p>
	 *
	 * <pre>
	 * StringUtils.isNotBlank(null)      = false
	 * StringUtils.isNotBlank("")        = false
	 * StringUtils.isNotBlank(" ")       = false
	 * StringUtils.isNotBlank("bob")     = true
	 * StringUtils.isNotBlank("  bob  ") = true
	 * </pre>
	 *
	 * @param cs
	 *            the CharSequence to check, may be null
	 * @return {@code true} if the CharSequence is not empty and not null and
	 *         not whitespace
	 * @see Character#isWhitespace
	 */
	public static boolean isNotBlank(final CharSequence cs) {
		return StringUtil.hasText(cs);
	}

	/**
	 * Convert a {@code Collection} into a delimited {@code String} (e.g. CSV).
	 * <p>
	 * Useful for {@code toString()} implementations.
	 * 
	 * @param coll
	 *            the {@code Collection} to convert
	 * @param delim
	 *            the delimiter to use (typically a ",")
	 * @return the delimited {@code String}
	 */
	public static String join(Collection<?> coll, String delim) {
		return StringUtil.collectionToDelimitedString(coll, delim);
	}

	/**
	 * Convert a {@code String} array into a delimited {@code String} (e.g.
	 * CSV).
	 * <p>
	 * Useful for {@code toString()} implementations.
	 * 
	 * @param arr
	 *            the array to display
	 * @param delim
	 *            the delimiter to use (typically a ",")
	 * @return the delimited {@code String}
	 */
	public static String join(Object[] arr, String delim) {
		return StringUtil.arrayToDelimitedString(arr, delim);
	}

	/**
	 * 生成uuid
	 * 
	 * @return UUID
	 */
	public static String getUUId() {
		return UUID.randomUUID().toString();
	}

	public static String paramToStr(Map<String, String[]> parameterMap) {

		if (parameterMap == null) {
			return "";
		}
		StringBuilder paramStr = new StringBuilder();

		for (Map.Entry<String, String[]> param : ((Map<String, String[]>) parameterMap).entrySet()) {
			if ("password".equals(param.getKey()) || "pwd".equals(param.getKey()) || "oldPwd".equals(param.getKey())) {
				continue;
			}
			paramStr.append(("".equals(paramStr.toString()) ? "" : "&") + param.getKey() + "=");
			String paramValue = (param.getValue() != null && param.getValue().length > 0 ? param.getValue()[0] : "");
			paramStr.append(abbr(paramValue, 100));
		}

		return paramStr.toString();
	}

	public static String abbr(String str, int length) {
		if (str == null) {
			return "";
		}
		try {
			StringBuilder sb = new StringBuilder();
			int currentLength = 0;
			for (char c : replaceHtml(StringEscapeUtils.unescapeHtml4(str)).toCharArray()) {
				currentLength += String.valueOf(c).getBytes("UTF-8").length;
				if (currentLength <= length - 3) {
					sb.append(c);
				} else {
					sb.append("...");
					break;
				}
			}
			return sb.toString();
		} catch (UnsupportedEncodingException e) {
			log.error(e.getMessage(), e);
		}
		return "";
	}

	/**
	 * 替换掉HTML标签方法
	 */
	public static String replaceHtml(String html) {
		if (isBlank(html)) {
			return "";
		}
		String regEx = "<.+?>";
		Pattern p = Pattern.compile(regEx);
		Matcher m = p.matcher(html);
		String s = m.replaceAll("");
		return s;
	}

	public static String paramToStr() {
		// TODO Auto-generated method stub
		return null;
	}

}
